<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          maxlength="200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原名" prop="originalName">
        <el-input
          v-model="queryParams.originalName"
          placeholder="请输入原名"
          clearable
          maxlength="200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件后缀" prop="fileSuffix">
        <el-input
          v-model="queryParams.fileSuffix"
          placeholder="请输入文件后缀"
          clearable
          maxlength="200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="上传人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入上传人"
          clearable
          maxlength="200"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片类型" prop="shelf">
        <el-select v-model="queryParams.imgType" placeholder="图片类型" clearable>
          <el-option
            v-for="dict in dict.type.app_image_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleFile"
          v-hasPermi="['system:oss:upload']"
        >上传文件</el-button>
      </el-col>
      -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImage"
          v-hasPermi="['system:oss:upload']"
        >上传图片</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:oss:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :type="previewListResource ? 'danger' : 'warning'"
          plain
          size="mini"
          @click="handlePreviewListResource(!previewListResource)"
          v-hasPermi="['system:oss:edit']"
        >预览开关 : {{previewListResource ? "禁用" : "启用"}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="handleOssConfig"
          v-hasPermi="['system:oss:list']"
        >配置管理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="tables"
      v-loading="loading"
      :data="ossList"
      @selection-change="handleSelectionChange"
      :default-sort="defaultSort"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="对象存储主键" align="center" prop="ossId" v-if="false"/>
      <el-table-column label="文件名" align="center" prop="fileName"/>
      <el-table-column label="原名" align="center" prop="originalName"/>
      <el-table-column label="文件后缀" align="center" prop="fileSuffix"/>
      <el-table-column label="文件展示" align="center" prop="url">
        <template slot-scope="scope">
          <el-image
            v-if="previewListResource && checkFileSuffix(scope.row.fileSuffix)"
            style="width: 100px; height: 100px;"
            :src="scope.row.url"
            :preview-src-list="[scope.row.url]"
          />
          <span
            v-text="scope.row.url"
            v-if="!checkFileSuffix(scope.row.fileSuffix) || !previewListResource"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
        sortable="custom"
        :sort-orders="['descending', 'ascending']"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="createBy"/>
      <el-table-column label="文件类型" align="center" prop="imgType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_image_type" :value="scope.row.imgType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownload(scope.row)"
            v-hasPermi="['system:oss:download']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:oss:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-select v-model="upload.data.imgType" placeholder="图片类型" clearable>
        <el-option
          v-for="dict in dict.type.app_image_type"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      <br>
      <br>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jpg, .png, .gif, .jpeg"
        :auto-upload="false"
        drag
        :headers="upload.headers"
        :action="upload.url"
        :data="upload.data"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :before-upload="beforeFileUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入 jpg、png、jpeg、gif 格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOss, delOss } from "@/api/system/oss";
import { getToken } from "@/utils/auth";

export default {
  name: "Oss",

  dicts: ["app_image_type"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // OSS对象存储表格数据
      ossList: [],
      // 预览列表图片
      previewListResource: true,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 默认排序
      defaultSort: { prop: "createDate", order: "descending" },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: undefined,
        originalName: undefined,
        fileSuffix: undefined,
        url: undefined,
        createTime: undefined,
        createBy: undefined,
        imgType: "",
        orderByColumn: "createDate",
        isAsc: "descending"
      },
      // 用户导入参数
      upload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/resource/oss/upload", // 上传的图片服务器地址
        headers: { Authorization: "Bearer " + getToken() }, // 设置上传的请求头部
        data: {
          imgType: ""
        } // 上传的额外数据，用于文件名
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询OSS对象存储列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && "" != this.daterangeCreateTime) {
        this.queryParams.params[
          "beginCreateTime"
        ] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      this.getConfigKey("sys.oss.previewListResource").then(response => {
        this.previewListResource =
          response.message === undefined ? true : response.message === "true";
      });
      listOss(this.queryParams).then(response => {
        this.ossList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    checkFileSuffix(fileSuffix) {
      let arr = ["png", "jpg", "jpeg", "gif", "PNG", "JPG", "JPEG", "GIF"];
      return arr.some(type => {
        return fileSuffix.toLowerCase().indexOf(type) > -1;
      });
    },
    // 取消按钮
    cancel() {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.data.imgType = "";
      this.$refs.upload.clearFiles();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.queryParams.imgType = "";
      this.resetForm("queryForm");
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ossId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 任务日志列表查询 */
    handleOssConfig() {
      this.$router.push({ path: "/system/oss-config/index" });
    },
    /** 图片按钮操作 */
    handleImage() {
      this.upload.open = true;
      this.upload.title = "上传文件";
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      this.$download.oss(row.ossId);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ossIds = row.ossId || this.ids;
      this.$modal
        .confirm('是否确认删除OSS对象存储编号为"' + ossIds + '"的数据项?')
        .then(() => {
          this.loading = true;
          return delOss(ossIds);
        })
        .then(() => {
          this.loading = false;
          this.handleQuery();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 预览列表图片状态修改
    handlePreviewListResource(previewListResource) {
      let text = previewListResource ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""预览列表图片"配置吗?')
        .then(() => {
          return this.updateConfigByKey(
            "sys.oss.previewListResource",
            previewListResource
          );
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(() => {
          this.previewListResource = previewListResource !== true;
        });
    },
    beforeFileUpload(file) {
      if (file == undefined) {
        this.$modal.msgError("文件不能为空！");
        return false;
      }
      //校验文件大小
      if (file.size >= 5242880) {
        this.$modal.msgError("文件大小超出5M，请重新上传！");
        return false;
      }
      //校验文件格式
      if (
        file.type != "image/png" &&
        file.type != "image/jpg" &&
        file.type != "image/jpeg" &&
        file.type != "image/gif"
      ) {
        this.$modal.msgError("提示：仅允许导入 jpg、png、jpeg、gif 格式文件！");
        return false;
      }
    },

    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {},
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },
    /** 发起文件上传 */
    submitFileForm() {
      if (this.upload.data.imgType == "") {
        this.$modal.msgError("文件类型不能为空!");
        return false;
      }
      this.$refs.upload.submit();
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      // 清理
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.data.imgType = "";
      this.$refs.upload.clearFiles();
      // 提示成功，并刷新
      this.$modal.msgSuccess("上传成功");
      this.getList();
    }
  }
};
</script>
<style>
  .el-image > img{
    object-fit: contain;
  }
</style>
